<?php

namespace app\common\model\Subject;

use think\Model;
// 引入软删除
use traits\model\SoftDelete;

class Subject extends Model
{
    // 使用软删除
    use SoftDelete;

    protected $name = 'subject';
    protected $autoWriteTimestamp = true;
    protected $createTime = 'createtime';
    protected $updateTime = false;

    // 设置软删除字段
    protected $deleteTime = 'deletetime';

    protected $append = [
        'thumbs_text', // 封面
        'likes_text', // 点赞数
        'createTime_text', // 创建时间
    ];

    public function getThumbsTextAttr($value, $data)
    {
        $thumbs = !empty($data['thumbs']) ? $data['thumbs'] : '/assets/img/cover.png';

        return $thumbs;
    }

    public function getLikesTextAttr($value, $data)
    {
        $likes = !empty($data['likes']) ? trim($data['likes']) : '';

        if ($likes) {
            $likes = explode(',', $likes);
            return count($likes);
        } else {
            return 0;
        }
    }

    public function getCreateTimeTextAttr($value, $data)
    {
        $createTime = !empty($data['createtime']) ? date('Y-m-d H:i:s', $data['createtime']) : '';

        return $createTime;
    }

    public function category()
    {
        return $this->belongsTo('app\common\model\Subject\Category', 'cateid', 'id', [], 'LEFT')
            ->setEagerlyType(0);
    }

    public function teacher()
    {
        return $this->belongsTo('app\common\model\Subject\Teacher\Teacher', 'teacherid', 'id', [], 'LEFT')
            ->setEagerlyType(0);
    }
}
